package visual.com.avrecorder;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import visual.com.avrecorder.record.AlreadyUsedException;
import visual.com.avrecorder.record.CLog;
import visual.com.avrecorder.record.CameraWrapper;
import visual.com.avrecorder.record.CaptureConfiguration;
import visual.com.avrecorder.record.NativeCamera;
import visual.com.avrecorder.record.RecordingButtonInterface;
import visual.com.avrecorder.record.Utils;
import visual.com.avrecorder.record.VideoCaptureView;
import visual.com.avrecorder.record.VideoFile;
import visual.com.avrecorder.record.VideoRecorder;
import visual.com.avrecorder.record.VideoRecorderInterface;


@SuppressLint("NewApi")
public class RecordActivity extends AppCompatActivity implements RecordingButtonInterface, VideoRecorderInterface {

    private boolean mVideoRecorded = false;
    VideoFile mVideoFile = null;
    private CaptureConfiguration mCaptureConfiguration;

    private VideoCaptureView mVideoCaptureView;
    private VideoRecorder mVideoRecorder;
    private Chronometer mChronometer;
    public long timeLeftInS = 0;
    private static final int PERMISSIONS_REQUEST_CAMERA = 102;

    public static void launch(Context context) {
        context.startActivity(new Intent(context, RecordActivity.class));
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CLog.toggleLogging(this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_record);
        mChronometer = findViewById(R.id.timer);
        mVideoCaptureView = findViewById(R.id.videocapture_view);
        if (mVideoCaptureView == null) {
            return;
        }
        if (checkSelfPermission()) {
            initializeRecordingUI();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSIONS_REQUEST_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initializeRecordingUI();
                } else {
                    RecordActivity.this.finish();
                    Toast.makeText(this, getString(R.string.please_open_permissions), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 检查权限
     */
    private boolean checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO},
                    PERMISSIONS_REQUEST_CAMERA);
            return false;
        } else {
            return true;
        }
    }


    private void initializeRecordingUI() {
        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        mCaptureConfiguration = new CaptureConfiguration();
        mVideoFile = new VideoFile(Utils.setRecordVideoFileName());
        mVideoRecorder = new VideoRecorder(this, mCaptureConfiguration, mVideoFile,
                new CameraWrapper(new NativeCamera(), display.getRotation()),
                mVideoCaptureView.getPreviewSurfaceHolder());
        mVideoCaptureView.setRecordingButtonInterface(this);

        if (mVideoRecorded) {
            mVideoCaptureView.updateUIRecordingFinished(getVideoThumbnail());
        } else {
            mVideoCaptureView.updateUINotRecording();
        }
    }

    @Override
    protected void onPause() {
        if (mVideoRecorder != null) {
            mVideoRecorder.stopRecording(null);
        }
        releaseAllResources();
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        finishCancelled();
    }

    @Override
    public void onRecordButtonClicked() {
        try {
            mVideoRecorder.toggleRecording();
        } catch (AlreadyUsedException e) {
            CLog.d(CLog.ACTIVITY, "Cannot toggle recording after cleaning up all resources");
        }
    }

    @Override
    public void onAcceptButtonClicked() {
//    	TSIConstant.recordvideos.add(mVideoFile.getFullPath());
//		TSIConstant.listDelete.add(false);
//		TSIConstant.listPlayFlag.add(false);
        finishCompleted();
    }

    @Override
    public void onDeclineButtonClicked() {
        finishCancelled();
    }

    @Override
    public void onRecordingStarted() {
        mVideoCaptureView.updateUIRecordingOngoing();
        initTimer(3600);
        mChronometer.start();
    }

    @Override
    public void onRecordingStopped(String message) {
        if (message != null) {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        }

        mChronometer.stop();
        mVideoCaptureView.updateUIRecordingFinished(getVideoThumbnail());
        releaseAllResources();
    }

    @Override
    public void onRecordingSuccess() {
        mVideoRecorded = true;
    }

    @Override
    public void onRecordingFailed(String message) {
        finishError(message);
    }

    private void finishCompleted() {
        finish();
    }

    private void finishCancelled() {
        this.setResult(RESULT_CANCELED);
        finish();
    }

    private void finishError(final String message) {
        Toast.makeText(getApplicationContext(), "Can't capture video: " + message, Toast.LENGTH_LONG).show();
        finish();
    }

    private void releaseAllResources() {
        if (mVideoRecorder != null) {
            mVideoRecorder.releaseAllResources();
        }
    }

    public Bitmap getVideoThumbnail() {
        final Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(mVideoFile.getFullPath(),
                Thumbnails.FULL_SCREEN_KIND);
        if (thumbnail == null) {
            CLog.d(CLog.ACTIVITY, "Failed to generate video preview");
        }
        return thumbnail;
    }

    private void initTimer(long total) {
        this.timeLeftInS = total;
        mChronometer.setOnChronometerTickListener(new OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                if (timeLeftInS <= 0) {
                    try {
                        mVideoRecorder.toggleRecording();
                    } catch (AlreadyUsedException e) {
                        CLog.d(CLog.ACTIVITY, "Cannot toggle recording after cleaning up all resources");
                    }
                    return;
                }
                timeLeftInS--;
                refreshTimeLeft();
            }
        });
    }

    private void refreshTimeLeft() {
        this.mChronometer.setText("录制时间为" + timeLeftInS + "秒");
    }
}
